package day01;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class joinTest {
    static int count = 0;
    static int r1 = 0;
    static int r2 = 0;


    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }

    /**
     * 涉及到线程上下文的切换
     */
    private static void test2() throws InterruptedException {

        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(1000);
                r1 = 20;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                r2 = 30;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        // 两个线程并行执行,进行睡觉
        t1.start();
        t2.start();
        long start = System.currentTimeMillis();
        log.debug("jogin begin");
        // t1等待他执行完毕
        t2.join();
        log.debug("t2 join end");
        t1.join();
        log.debug("t1 join end");
        long end = System.currentTimeMillis();
        log.debug( "cost: " + (end - start));
    }


    private static void test1() throws InterruptedException {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(1000);
                    count = 20;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        t1.start();
        t1.join();
        log.debug(String.valueOf(count));
    }


}
